package com.link.base.base.address.controller;

import com.link.base.user.model.CoreUser;
import com.link.base.base.address.model.AddrPst;
import com.link.base.base.address.service.AddrPstService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.query.Sorter;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.AppConstants;
import com.link.core.util.RedisUtil;
import com.link.core.util.UserUtil;
import com.link.core.util.redisclient.LinkRedisClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Copyright  hande Company. All Rights Reserved.
 *
 * @author unknwon
 * @version 1.0
 * @date: 2018/11/8 10:15
 */

@Controller
@RequestMapping("/link/address")
public class AddressController extends BasicController<AddrPst> {


    @Resource
    private AddrPstService addrPstService;

    @Override
    public BasicService<AddrPst> getBasicService() throws Exception {
        return addrPstService;
    }


    @RequestMapping(value = "/init")
    public String init(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        return "addrpst/AddrPst";
    }

    /**
     * 子地址列表
     *
     * @param qps
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/childList")
    @ResponseBody
    public List<AddrPst> childList(@JsonParam QueryParams qps, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        List<AddrPst> list = null;
        //按创建时间来排序
        Sorter sorter = new Sorter("addrName", Sorter.DIR_ASC);
        qps.addSorter(sorter);
        try {
            list = addrPstService.queryChildAddrListSelect(qps);
        } catch (Exception e) {
            LCLogger.withException(e);
        }
        return list;
    }

    /**
     * 省地址列表
     *
     * @param qps
     * @param session
     * @param request
     * @param response
     */
    @RequestMapping(value = "/provinceList")
    public void provinceList(@JsonParam QueryParams qps, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        LinkRedisClient j = RedisUtil.getJedis();
        String flag = "Y";
        try {
            CoreUser user = UserUtil.getUser();
            String redisKey = AddrPstService.ADDR_CACHE_KEY;
            if (user != null && flag.equals(user.getPrivateAddr())) {
                redisKey += "_" + user.getLoginCorpId();
            }
            String json = j.hget(redisKey, "State");
            json = json == null ? "[]" : json;
            responseJson(request, response, json);

        } catch (Exception e) {
            LCLogger.withException(e);
        } finally {
            RedisUtil.returnResource(j);
        }
    }

    /**
     * 县区
     *
     * @param qps
     * @param session
     * @param request
     * @param response
     */
    @RequestMapping(value = "/countryList")
    public void countryList(@JsonParam QueryParams qps, HttpSession session, HttpServletRequest request, HttpServletResponse response) {

        LinkRedisClient j = RedisUtil.getJedis();
        String flag = "Y";

        try {

            CoreUser user = UserUtil.getUser();
            String redisKey = AddrPstService.ADDR_CACHE_KEY;
            if (user != null && flag.equals(user.getPrivateAddr())) {
                redisKey += "_" + user.getLoginCorpId();
            }
            String json = j.hget(redisKey, "Country");
            json = json == null ? "[]" : json;
            responseJson(request, response, json);
        } catch (Exception e) {
            LCLogger.withException(e);
        } finally {
            RedisUtil.returnResource(j);
        }
    }

    /**
     * 查地址列表
     *
     * @param parentAddrName
     * @param parentAddr2Name
     * @param addrType
     * @param session
     * @param request
     * @param response
     */
    @RequestMapping(value = "/queryAddressListSelect")
    public void queryAddressListSelect(String parentAddrName, String parentAddr2Name, String addrType,
                                       HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        LinkRedisClient j = RedisUtil.getJedis();
        String flag = "Y";
        try {
            CoreUser user = UserUtil.getUser();
            String redisKey = AddrPstService.ADDR_CACHE_KEY;
            if (user != null && flag.equals(user.getPrivateAddr())) {
                redisKey += "_" + user.getLoginCorpId();
            }
            parentAddrName = parentAddrName == null ? "" : parentAddrName;
            String field = parentAddrName;
            String json = j.hget(redisKey, field);
            json = json == null ? "[]" : json;
            responseJson(request, response, json);

        } catch (Exception e) {
            LCLogger.withException(e);
        } finally {
            RedisUtil.returnResource(j);
        }
    }

    /**
     * <p>刷新地址缓存</p>
     *
     * @param session
     * @param request
     * @param response
     * @return
     * @author yrf
     */
    @RequestMapping(value = "/refreshCache")
    @ResponseBody
    public Map<String, Object> refreshCache(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("refreshCache").withMessage("更新地址缓存信息...").flush();
        Map<String, Object> result = new HashMap<String, Object>(4);
        String flag = "Y";
        try {
            CoreUser user = UserUtil.getUser();
            if (!flag.equals(user.getPrivateAddr()) && !AppConstants.ADMIN_CORP_ID.equals(user.getCorpid())) {
                throw new ServiceException("ADDRESS-001");
            }
            addrPstService.cacheAddrPst(true, user.getLoginCorpId());
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }
}
